package com.maikang.exammall.api;

import com.maikang.exammall.entity.Comment;
import com.maikang.exammall.entity.dto.CreateCommentsInputDTO;
import com.maikang.exammall.entity.dto.FindAllRequest;
import com.maikang.exammall.entity.dto.ResponseDTO;
import com.maikang.exammall.service.CommentService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

import static com.maikang.exammall.entity.constant.ApiCacheKeyConstant.commentApiKey;
import static org.apache.commons.lang3.ObjectUtils.isEmpty;

@RestController
@RequiredArgsConstructor
@Log4j2
@RequestMapping("/api/comments")
public class CommentController {

    final private CommentService service;

    @PostMapping(value = "/pkg-id/search")
    @ApiOperation("评论列表, payload 内pageable和conditions 必须传")
    @Cacheable(value = commentApiKey, key = "'findAll:payload:'+#findAllRequest.hashCode()")
    public ResponseDTO<Iterable<Comment>> findAll(@RequestBody FindAllRequest<Comment> findAllRequest) {
        Iterable<Comment> ret;
        if (findAllRequest == null || isEmpty(findAllRequest.getConditions()) && isEmpty(findAllRequest.getPageable())) {
            throw new RuntimeException("querying comment list without pagination");
        } else if (findAllRequest.getPageable() != null) {
            ret = this.findAllByPkgId(findAllRequest.getConditions(), findAllRequest.getPageable().getPageable());
        } else {
            log.warn("querying comment list without pagination");
            throw new RuntimeException("querying comment list without pagination");
        }
        return ResponseDTO.ok(ret);
    }

    private Iterable<Comment> findAllByPkgId(Comment comment, Pageable pageable) {
        return service.findByPkgId(comment.getPkgId(), pageable);
    }

    @ApiOperation("创建评论")
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<Iterable<Comment>> saveAll(@Valid @RequestBody CreateCommentsInputDTO inputDTO) {
        return ResponseDTO.ok(service.saveAll(inputDTO.getGroupedOrderItemsList()));
    }
}
